package ee.rawre.tafayc.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.Cookies;

public class CookieManager {
   
   private final String SEPARATOR = " ";
   private final String nothingFound = "Nothing found.";
   private long curTime;
   private String cookies;
   private String tmpCookie;
   private List<String> names;
   
   public void setCookie(int... cookies) {
      String cookieValue = new String();
      
      for (int i=0; i<cookies.length; i++) {
         if (i>0) cookieValue += SEPARATOR;
         cookieValue += cookies[i];
      }
      curTime = System.currentTimeMillis();
      Cookies.setCookie(Long.toString(curTime), cookieValue, new Date(curTime+(long)365*24*60*60*1000));
   }

   public List<String> getCookies() throws Exception {
      Collection<String> namesC = Cookies.getCookieNames();
//      List<String> names = (List<String>) Cookies.getCookieNames();
      names = new ArrayList<String>();
      for (String cookie : namesC) {
         if(TypeVerifier.isNumeric(cookie)) { // basic cookie filtering
            names.add(cookie);
            System.out.println(cookie); // UNORDERED //dbg
         }
      }
//      String tmp = names.get(0);
//      names.set(0, names.get(1));
//      names.set(1, tmp);
      
      // dbg
      System.out.println("--------------");
      Collections.sort(names);
      for (String cookie : names) {
         System.out.println(cookie); // ORDERED // dbg
      } //dbg
      
      if (names.size() == 0) throw new Exception(nothingFound);
      
      return names;
   }
   
   public Map<String, int[]> getCookieMap() {
      Map<String, int[]> cookieMap = new HashMap<String, int[]>();
      int[] value = null;
      try {
         names = getCookies();
         cookies = "";
         for (int i=0; i<names.size(); i++) {
            tmpCookie = names.get(i);
            if(i!=0) cookies += "<br>";
            value = TypeVerifier.convertStringArraytoIntArray(
                  Cookies.getCookie(tmpCookie).split(SEPARATOR));
            cookieMap.put(tmpCookie, value);
         }
         
         return cookieMap;
      } catch (Exception e) {
         return null;
      }
   }
   
   public String toString() {
      try {
         getCookies();
         cookies = "";
         for (int i=0; i<names.size(); i++) {
            tmpCookie = names.get(i);
            if(TypeVerifier.isNumeric(tmpCookie)) {
               if(i!=0) cookies += "<br>";
               cookies += tmpCookie + ": " + Cookies.getCookie(tmpCookie);
            }
         }
         return cookies;
      } catch (Exception e) {
         return nothingFound;
      }
   }
}
